<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use GuzzleHttp\Client;


class UploadController extends AppBaseController
{


    public function index(Request $request, $type)
    {

        $this->validate($request,
            ['file' => 'required|image|max:5120'],
            ['file' => '图片']
        );

        $client = new Client(['base_uri' => config('custom.file_upload_url')]);

        //验证规则
        $res = $client->request('POST', 'upload', [
            'multipart' => [
                [
                    'name' => 'token',
                    'contents' => config('custom.file_upload_token'),
                ],
                [
                    'name' => 'file',
                    'contents' => fopen($request->file('file')->getRealPath(), 'r')
                ]
            ]
        ]);

        //请求失败
        if ($res->getStatusCode() !== 200) {
            return $this->sendApiError('上传错误');
        }

        $response = $res->getBody()->getContents();
        $res = \GuzzleHttp\json_decode($response, true);

        //上传失败
        if ($res['status'] !== 0) {
            return $this->sendApiError('上传失败');
        }

        if(!$res['data']){
            return $this->sendApiError('上传错误');
        }

        //返回数据
        $data = [
            'url' => $res['data'],
            'name' => basename($res['data'])
        ];


        return $this->sendResponse($data, '上传成功');
    }
}
